import React from 'react';
/**
 * 计算字符串的字节数，非中文字符占1个字节，中文字符占2个字节
 * @param {string}
 * 返回传入字符串的长度
 */
const checkStrLength = function (str) {
  let iLength = 0;
  const strLength = str.length;
  for (let i = 0; i < strLength; i++) {
    if (str.charCodeAt(i) > 255) {
      iLength = iLength + 2;
    } else {
      iLength = iLength + 1;
    }
  }
  return iLength;
};

const Input = React.createClass({
  getDefaultProps() {
    return {
      type: 'text',
      onClick: false,
      onChange: false,
      onFocus: false,
      onBlur: false,
      placeholder: false,
      defaultVlaue: false,
      disabled: false
    };
  },
  getInitialState() {
    return {
      showValidate: false,
      validateInfo: '',
      value: this.props.value
    };
  },
  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  },
  /**
   * 失去焦点验证输入值
   * @param {object} eg:v1.data[正则表达式] = 提示信息
   * 返回是否显示提示信息
   */
  handleBlur(e) {
    e = e || event;
    const data = {};
    data.target = e.target || e.srcElement;
    data.value = (data.target.type === 'text' || data.target.type === 'textarea') ? data.target.value.trim() : data.target.value;
    data.name = this.props['data-target'];
    this.setState({ value: data.value });
    if (this.props.onBlur) {
      this.props.onBlur(data);
    }
    if (!this.props.validate) {
      return;
    }
    const
      value = data.value, // 目标值
      valueLength = value.length,
      exg = this.props.validate.data,
      minLengthByte = this.props.validate.minLengthByte, // 最小字节数
      maxLengthByte = this.props.validate.maxLengthByte, // 最大字节数
      minLengthChar = this.props.validate.minLengthChar, // 最小字符数
      maxLengthChar = this.props.validate.maxLengthChar; // 最大字符数
    if (minLengthChar.min === 0 && !valueLength) {
      this.setState({ showValidate: false });
      return;
    }
    if (exg) {
      for (const key in exg) {
        if (!RegExp(key).test(value)) {
          this.setState({
            validateInfo: exg[key],
            showValidate: true
          });
          return;
        } else {
          this.setState({ showValidate: false });
        }
      }
    }
    // 判断最少允许的字节数
    // ==================
    if (minLengthByte && checkStrLength(value) < minLengthByte.min) {
      this.setState({
        validateInfo: minLengthByte.message,
        showValidate: true
      });
      return;
    } else {
      this.setState({ showValidate: false });
    }
    if (maxLengthByte && checkStrLength(value) > maxLengthByte.max) {
      this.setState({
        validateInfo: maxLengthByte.message,
        showValidate: true
      });
      return;
    } else {
      this.setState({
        showValidate: false
      });
    }
    // 判断最小允许的字符数
    // ================
    if (minLengthChar && valueLength < minLengthChar.min) {
      this.setState({
        validateInfo: minLengthChar.message,
        showValidate: true
      });
      return;
    } else {
      this.setState({
        showValidate: false
      });
    }
    // 判断最大允许的字符数
    // ================
    if (maxLengthChar && valueLength > maxLengthChar.max) {
      this.setState({
        validateInfo: minLengthChar.message,
        showValidate: true
      });
      return;
    } else {
      this.setState({
        showValidate: false
      });
    }
  },
  handleChange(e) {
    e = e || event;
    const data = {};
    data.target = e.target || e.srcElement;
    data.value = data.target.value;
    data.name = this.props['data-target'];
    this.setState({ value: data.value });
    if (this.props.onChange) {
      this.props.onChange(data);
    }
  },

  render() {
    const props = {},
      validateDom = <div className="form-error fadeInRight text-danger">{this.state.validateInfo}</div>;
    props['type'] = this.props.type;
    // if(this.props.value){
    //     props['value'] = this.props.value;
    // }
    // 事件处理
    if (this.props.onClick) {
      props.onClick = this.props.onClick;
    }
    if (this.props.onChange) {
      props.onChange = this.props.onChange;
    }
    if (this.props.onFocus) {
      props.onFocus = this.props.onFocus;
    }
    if (this.props.onBlur) {
      props.onBlur = this.props.onBlur;
    }

    // 参数处理
    if (this.props.placeholder) {
      props.placeholder = this.props.placeholder;
    }
    if (this.props.value) {
      props.value = this.props.value;
    }
    if (this.props.defaultValue) {
      props.defaultValue = this.props.defaultValue;
    }
    if (this.props.disabled) {
      props.disabled = 'disabled';
    }
    props['data-target'] = this.props['data-target'];
    props.onChange = this.handleChange;
    // 验证
    // ========
    if (this.props.validate) {
      props.onFocus = this.handleFocus;
      props.onBlur = this.handleBlur;
    }
    props.onBlur = this.handleBlur;
    if (this.props.type === 'textarea') {
      const diyName = this.props.className ? (this.props.className + ' ') : '';
      return (
        <div className={diyName + 'mt-textarea' + (this.state.showValidate ? ' mt-input-error' : '')}>
          <textarea {...props} className="form-control" rows={this.props.rows} value={this.state.value} />
          {this.state.showValidate ? validateDom : ''}
        </div>
      );
    }

    const diyName = this.props.className ? (this.props.className + '') : '';
    const cName = diyName + 'mt-input';
    return (
      <div className={cName + (this.state.showValidate ? ' mt-input-error' : '')}>
        <input
          {...props}
          className={this.props.className ? this.props.className + ' form-control' : 'form-control'}
          value={this.state.value}
          maxLength={this.props.maxLength}
          autoFocus={this.props.autoFocus}
        />
        {this.state.showValidate ? validateDom : ''}
      </div>
    );
  }
});

export default Input;
